/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.trick.admin.controller;

import it.trick.admin.App;
import it.trick.admin.model.PageModel;
import it.trick.admin.model.PreModel;
import it.trick.admin.task.GetPreModelTask;
import it.trick.admin.task.UpdatePreTask;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;

/**
 * FXML Controller class
 *
 * @author takahara
 */
public class AddPreViewController extends AnchorPane implements Initializable {

    /**
     * 名前
     */
    @FXML
    private TextField preNameTextField;
    @FXML
    public Button addButton;
    @FXML
    public Button updateButton;
    /**
     * ソースエディター
     */
    @FXML
    private TextArea preEditTextArea;
    private boolean editFlg = false;
    private PageModel pageModel;
    private GetPreModelTask getPreModelTask;
    private UpdatePreTask updatePreTask;
    private PreModel preModel;

    /**
     * コンストラクタ
     */
    public AddPreViewController(PageModel pageModel) {
        this.pageModel = pageModel;
        init();
    }

    /**
     * コンストラクタ（更新用）
     */
    public AddPreViewController(PreModel preModel) {
        this.preModel = preModel;
        editFlg = true;
        init();
    }

    /**
     * コントロールの初期化
     */
    private void init() {

        // ---------------------------------------------------
        // FXMLのロードと設定
        // ---------------------------------------------------
        FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource("resource/fxml/add_pre_view.fxml"));
        fxmlLoader.setRoot(this);
        // 自分自身をコントロールとして設定
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        if (editFlg) {
            addButton.setText("更新");
            addButton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent e) {
                    updateAction();
                }
            });

            getPreModelTask = new GetPreModelTask();
            getPreModelTask.setup(preModel.getPrarentKeyString());
            getPreModelTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent t) {

                    // サービスの処理結果を受け取る
                    preModel = (PreModel) t.getSource().getValue();

                    // Tree Root Nodeを設定する
                    preNameTextField.setText(preModel.getName());
                    preEditTextArea.setText(preModel.getContent());
                }
            });

            getPreModelTask.restart();

            preNameTextField.setText(preModel.getName());
            preEditTextArea.setText(preModel.getContent());

        } else {
            addButton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent e) {
                    addAction();
                }
            });
        }
    }

    /**
     * 追加
     */
    private void addAction() {
        PreModel model = new PreModel();
        model.setPrarentKeyString(pageModel.getKeyValueString());
        model.setName(preNameTextField.getText());
        model.setIndex(EditPageViewController.getInstance().preListView.getItems().size() + 1);
        model.setContent(preEditTextArea.getText());
        ChannelTopController.getInstance().addPreTask.setup(model);

        // ---------------------------------------------------------------------
        // サービスの正常処理イベント
        // ---------------------------------------------------------------------
        ChannelTopController.getInstance().addPreTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                // サービスの処理結果を受け取る
                PreModel preModel = (PreModel) t.getSource().getValue();

                EditPageViewController.getInstance().preListView.getItems().add(preModel);
            }
        });

        // ---------------------------------------------------------------------
        // サービスの例外イベント
        // ---------------------------------------------------------------------
        ChannelTopController.getInstance().addPreTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                Exception ex = (Exception) ChannelTopController.getInstance().addPreTask.getException();
                App.getInstance().showErrorPop(ex);
            }
        });

        App.getInstance().closePopStage();
        ChannelTopController.getInstance().addPreTask.restart();
    }

    /**
     * 更新
     */
    private void updateAction() {

        preModel.setName(preNameTextField.getText());
        preModel.setContent(preEditTextArea.getText());

        updatePreTask = new UpdatePreTask();
        updatePreTask.setup(preModel);

        // ---------------------------------------------------------------------
        // サービスの正常処理イベント
        // ---------------------------------------------------------------------
        updatePreTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                EditPageViewController.getInstance().loadPreListView();
                App.getInstance().closePopStage();
            }
        });

        // ---------------------------------------------------------------------
        // サービスの例外イベント
        // ---------------------------------------------------------------------
        updatePreTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                Exception ex = (Exception) ChannelTopController.getInstance().addPreTask.getException();
                App.getInstance().showErrorPop(ex);
            }
        });

        updatePreTask.restart();
    }

    /**
     * キャンセルアクション
     */
    @FXML
    protected void cancelAction() {
        App.getInstance().closePopStage();
    }
}
